package com.jy.adscm.operation.cgxsb.service.impl;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.cgxsb.bean.SporadicPurchaseAttchment;
import com.jy.adscm.operation.cgxsb.mapper.mysql.SporadicPurchaseAttchmentMapper;
import com.jy.adscm.operation.cgxsb.service.SporadicPurchaseAttchmentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-03-12
 */
@Service
public class SporadicPurchaseAttchmentServiceImpl extends ServiceImpl<SporadicPurchaseAttchmentMapper, SporadicPurchaseAttchment> implements SporadicPurchaseAttchmentService {
      @Autowired
    JyUserMapper jyUserMapper;
    @Override
    public List<SporadicPurchaseAttchment> selectByFileId(Integer fileId) {
        Wrapper<SporadicPurchaseAttchment> wrapper =new EntityWrapper<>();
        wrapper.eq("tid",fileId);
        List<SporadicPurchaseAttchment> sporadicPurchaseAttchments = super.selectList(wrapper);
        for (SporadicPurchaseAttchment sporadicPurchaseAttchment : sporadicPurchaseAttchments) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(sporadicPurchaseAttchment.getUploadPerson(),null)){
                JyUser jyUser = jyUserMapper.selectById(sporadicPurchaseAttchment.getUploadPerson());
                sporadicPurchaseAttchment.setUploadPersonName(jyUser.getName());
            }
        }
        return sporadicPurchaseAttchments;
    }

    @Override
    public Boolean deleteSporadicPurchaseAttchments(Integer id, Token token)throws AdscmSystemException {
        boolean delete= false;
        SporadicPurchaseAttchment sporadicPurchaseAttchment = super.selectById(id);
        if (AdscmBaseUtils.getInstance().isNotEmpty(sporadicPurchaseAttchment.getUploadPerson(),null)){
            if (sporadicPurchaseAttchment.getUploadPerson().equals(token.getUser().getId().toString())){
                File file=new File(sporadicPurchaseAttchment.getFilePath());
                if (file.exists()){
                    file.delete();
                }
                delete  = super.deleteById(id);
            }else {
                throw  new AdscmSystemException("您不能删除！");
            }
        }
        return delete;
    }
}
